String.prototype.trim = function() { 
	return this.replace(/(^\s*)|(\s*$)/g, "");  
};

var vCodeStr = "";

function loginSubmitHandler(form) {
  /*var vcodeStr = $("#inputVcode").val().trim().toLowerCase();
  if("" == vcodeStr)
  {
	  $("#com_raisecom_login_pass_error").css("display","");
	  $("#com_raisecom_login_pass_error").text(login_i18n.prop("com_raisecom_ums_aos_portal_login_validateCode_req"));
	  setTimeout(function()
	  {
         $("#com_raisecom_login_pass_error").css("display","none");
	  },3000);
	  return false;
  }
  if(vcodeStr != vCodeStr)
  {
	  $("#com_raisecom_login_pass_error").css("display","");
	  $("#com_raisecom_login_pass_error").text(login_i18n.prop("com_raisecom_ums_aos_portal_login_validateCode_error"));
	  setTimeout(function()
	  {
         $("#com_raisecom_login_pass_error").css("display","none");
	  },3000);
	  return false;
  }*/
  if("" != getCookie("username"))
  {
	  var data = {};
	  data.result = LOGIN_MSG_FAILED_OTHER_LOGIN;
	  processLoginResult(data);
      return false;
  }
  
  var params = {};
  params["username"] =$("#inputUserName").val().trim();
  var sourcePass = $("#inputPassword").val();
  var pass = sourcePass;
  if( FrameConst.isEncypt === "true"){
      pass = ict_framework_func1(pass);
  }
  params["password"] = pass;
  params["isEncypted"]  = FrameConst.isEncypt;				  
  params["vcode"]  = $("#inputVcode").val().trim();				  
  saveUserInfo(params);			          
  $.ajax({  
		url : FrameConst.REST_LOGIN,  
		type : 'POST',  
		data : JSON.stringify(params),  
		dataType : 'json',  
		contentType : 'application/json; charset=utf-8',  
		success : function(data, status, xhr) {  
		if(data.result == 0){
			 var epass=CryptoJS.MD5(params.username+sourcePass);
			 store("icttka", epass.toLocaleString());
		}
		else
		{
			getVcode();
			$("#inputVcode").val('');	
		}
			processLoginResult(data,params);
		},  
		Error : function(xhr, error, exception) {  
			if( console ){
				//console.log( "login fail:" + error );
				//console.log( exception ); 
			}
		}   
	});	   
};


var Login = function () {

	var handleLogin = function() {
		$('.login-form').validate({
	            errorElement: 'div', //default input error message container
	            errorClass: 'help-block', // default input error message class
				onfocusout:false,
				onkeyup:false,
				onclick:false,
	            focusInvalid: false, // do not focus the last invalid input
	            rules: {
	                username: {
	                    required: true
	                },
	                password: {
	                    required: function()
			    {
				var login_user_val = $('#inputUserName').val();
				var login_password_val = $('#inputPassword').val();
				if(!(login_user_val=='' && login_password_val==''))
				{
					return true;
				}
			    	else
				{
					return false;
				}
			    }
	                },
	                remember: {
	                    required: false
	                }
	            },

	            messages: {
	                username: {
	                   required: $.i18n.prop('com_raisecom_ums_ict_login_inputname').replace(/\"/g,'') 
	                },
	                password: {
	                   required: $.i18n.prop('com_raisecom_ums_ict_login_inputpwd').replace(/\"/g,'')
	                }
	            },

	            invalidHandler: function (event, validator) { //display error alert on form submit   
	                $('.alert-danger', $('.login-form')).show();
	            },

	            highlight: function (element) { // hightlight error inputs
	                $(element)
	                    .closest('.form-group').addClass('has-error'); // set error class to the control group
	            },

	            success: function (label) {
	                label.closest('.form-group').removeClass('has-error');
	                label.remove();
	            },

	            errorPlacement: function (error, element) 
		    {
	                // error.insertAfter(element.closest('.input-icon'));
					error.insertAfter(document.getElementById('com_raisecom_login_pass_error'));
					 //error.insertAfter(element[0].localName.next("span") );
	            },

	            submitHandler: loginSubmitHandler
	        });

	        $('.login-form input').keypress(function (e) {
		    	$("#nameOrpwdError").hide();
				$("#loginConnError").hide();
	            if (e.which == 13) {  
	                if ($('.login-form').validate().form()) {
	                    $('.login-form').submit();
	                }
	                return false;
	            }
	        });
			
			$("input[name='remember']").bind("click", function () {
			    saveUserInfo();
			});
	}

    return {
        //main function to initiate the module
        init: function () {
        	
            handleLogin();
			
			var n = i;
			setInterval(function()
			{
				if(n>3)
				n=1;
				var bg = document.body||document.documentElement;
				bg.style.background = "url('./img/login/raisecom_bg_"+n+".jpg')";
				n++;
			},15000); //10秒轮换一张
        }
    };
}();


$(document).ready(function() {
    if (store("remember") == "true") {
        $("input[name='remember']").attr("checked", "checked");
        $("#inputUserName").val(store("inputUserName"));
        $("#inputPassword").val(store("inputPassword"));
    }
    
    var lang = getLanguage();
	loadi18n_login(lang);
	Login.init();
			  
	if(store("inputUserName")){
	    $("#inputUserName").val(store("inputUserName"));
	}
	
	if("" != getCookie("username"))
	{
		window.location = FrameConst.DEFAULT_LOGINSKIP_PAGE;
	}
 
	
	/*$.ajax({ 	
		url : FrameConst.REST_GET_USERNAME,  
		type : "GET",
		cache:false,			
		contentType : 'application/json; charset=utf-8',
		success: function(data){
			var userName = data;
			if(userName !== null && userName !== undefined && userName !== ''){ 
				window.location = FrameConst.DEFAULT_LOGINSKIP_PAGE;
			}
			
			$("#inputUserName").focus();
		} 
	});	*/
	
	getVcode();
	$("#vcodeLink").click(function()
	{
		getVcode();
	});

    if (window.history && window.history.pushState) {
        $(window).on('popstate', function () {
            var hashLocation = location.hash;
            var hashSplit = hashLocation.split("#!/");
            var hashName = hashSplit[1];
            if (hashName !== '') {
                var hash = window.location.hash;
                if (hash === '') {
                    window.location = FrameConst.DEFAULT_LOGIN_PAGE;
                }
            }
        });
        window.history.pushState('forward', null, '');
    }	

});

function getVcode() {
	//$("#vcodeImg").attr('src', FrameConst.REST_GET_VCODE); 
	document.getElementById('vcodeImg').src=FrameConst.REST_GET_VCODE +"?"+Math.random();
	//return false;
}

function saveUserInfo(params) {
    var rmbcheck=$("input[name='remember']");
    if (rmbcheck.attr("checked")==true||rmbcheck.is(':checked')) {
	    var userName = $("#inputUserName").val();
        var passWord = $("#inputPassword").val();
        store("remember", "true"); 
        store("inputUserName", params.username); 
        store("inputPassword", passWord); 
    }
    else {
        store.remove("remember");
        store.remove("inputUserName");
        store.remove("inputPassword");
    }
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}